package com.resou.reader.base.v;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.resou.reader.R;
import com.resou.reader.base.ResouBaseActivity;
import com.resou.reader.base.p.BasePresenter;
import com.resou.reader.utils.NetworkUtils;
import com.resou.reader.utils.StatusBarCompat;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.log.RsLog;
import com.resou.reader.view.Loading;
import com.resou.reader.view.NetErrorFragment;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import com.umeng.socialize.UMShareAPI;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseActivity<P extends BasePresenter> extends AppCompatActivity implements IView {

    Unbinder unbinder;
    protected P presenter;
    protected Loading mLoading;
    protected View statusBarView = null;
    protected int statusBarColor = 0;
    private NetErrorFragment mNetErrorFragment;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initializePresenter();//这个方法一定要早
        setContentView(getLayoutId());
        unbinder = ButterKnife.bind(this);
        mLoading = Loading.getInstance();
        //初始化View
        initView();

        /**
         * 一般情况下，我们在Activity中会初始化Data（网络数据，数据库数据），但是由于我们使用MVP，所以初始化数据交给Presenter--->Model数据处理（在Model onCreate的时候处理）
         */
//        initData();

        // Umeng push
        PushAgent.getInstance(this).onAppStart();

    }

    /**
     * 同步M 、V、 P的生命周期
     */
    protected void initializePresenter() {
        initPresenter();
        if (presenter != null) {
            getLifecycle().addObserver(presenter);
            if (presenter.model != null) {
                getLifecycle().addObserver(presenter.model);
            }
        }
    }


    public abstract int getLayoutId();

    protected abstract void initPresenter();

    /**
     * 初始化View(设置Listener等等)
     */
    protected abstract void initView();

    protected abstract void retryRefreshData();


    @Override
    protected void onStart() {
        super.onStart();
        RsLog.i(getClass().getSimpleName() + "---onStart()");
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        RsLog.i(getClass().getSimpleName() + "---onNewIntent()");
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        RsLog.i(getClass().getSimpleName() + "---onStart()");
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        RsLog.i(getClass().getSimpleName() + "---onPause()");
    }

    @Override
    protected void onStop() {
        super.onStop();
        RsLog.i(getClass().getSimpleName() + "---onStop()");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        if (presenter != null) {
            getLifecycle().removeObserver(presenter);
            if (presenter.model != null) {
                getLifecycle().removeObserver(presenter.model);
            }
        }
        RsLog.i(getClass().getSimpleName() + "---onDestroy()");
    }

//      显示状态栏

    protected void showStatusBar() {
        // 全屏参数
        int flag = WindowManager.LayoutParams.FLAG_FULLSCREEN;
        // 获得当前窗体对象
        Window window = getWindow();
        // 设置当前窗体为全屏显示
        window.clearFlags(flag);
    }

    /**
     * 显示网络异常视图
     *
     * @param resId
     */
    public void showNetErrorView(int resId) {
        if (mNetErrorFragment == null) {
            mNetErrorFragment = new NetErrorFragment(new NetErrorFragment.OnClick() {
                @Override
                public void onClick() {
                    if (NetworkUtils.isNetworkConnected(BaseActivity.this)) {
                        dismissNetErrorView();
                        retryRefreshData();
                    } else {
                        ToastUtil.makeShortToast("网络异常");
                    }
                }
            });
        }
        mNetErrorFragment.show(resId, getSupportFragmentManager());
    }

    /**
     * 是否又网络
     *
     * @return
     */
    public boolean isNetwork() {
        if (NetworkUtils.isNetworkConnected(this)) {
            return true;
        } else {
            ToastUtil.makeShortToast("网络异常");
            return false;
        }
    }

    /**
     * 关闭无网络页码
     */
    public void dismissNetErrorView() {
        if (mNetErrorFragment != null) {
            mNetErrorFragment.dismiss();
        }
    }

    /**
     * 全屏显示
     */
    public void changeToFullScreen() {
        Window window = getWindow();
        if (window == null) {
            return;
        }
        View decorView = window.getDecorView();
        int systemUi = decorView.getSystemUiVisibility();
        systemUi |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            systemUi |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            systemUi |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
        }
        decorView.setSystemUiVisibility(systemUi);
        QMUIDisplayHelper.setFullScreen(this);
    }


    public void changeToNotFullScreen() {
        Window window = getWindow();
        if (window == null) {
            return;
        }
        final View decorView = window.getDecorView();
        int systemUi = decorView.getSystemUiVisibility();
        systemUi |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            systemUi &= ~View.SYSTEM_UI_FLAG_FULLSCREEN;
            systemUi |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            systemUi &= ~View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
            systemUi |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
        }
        decorView.setSystemUiVisibility(systemUi);
        QMUIDisplayHelper.cancelFullScreen(this);
        QMUIStatusBarHelper.setStatusBarLightMode(this);
        decorView.post(new Runnable() {
            @Override
            public void run() {
                ViewCompat.requestApplyInsets(decorView);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 显示进度条
     */
    public void showLoading() {
        if (!Loading.getInstance().isShow() && !Loading.getInstance().isRemoving() && !Loading.getInstance().isVisible() && !Loading.getInstance().isAdded()) {
            Loading.getInstance().show(getSupportFragmentManager());
        }
    }


    /***
     * 取消加载
     */
    public void dissLoading() {
        if (Loading.getInstance().isShow()) {
            Loading.getInstance().dismiss();
        }
    }

}
